package com.hksj.sftcm.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.hksj.base.query.AlarmQuery;
import com.hksj.base.query.BaseSpecialityQuery;
import com.hksj.base.query.ProductQuery;
import com.hksj.base.service.DefaultAlarmService;
import com.hksj.base.service.DefaultDeviceService;
import com.hksj.base.service.DefaultProductService;
import com.hksj.base.vo.AlarmRecordVO;
import com.hksj.base.vo.ProductVO;
import com.hksj.common.core.common.SpecialityModelCodeEnum;
import com.hksj.common.core.exception.ApplicationException;
import com.hksj.common.core.util.EasyExcelUtil;
import com.hksj.sftcm.mapper.SftcmMapper;
import com.hksj.sftcm.query.SftcmDailyAlarmQuery;
import com.hksj.sftcm.query.SpecialityProductQuery;
import com.hksj.sftcm.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SftcmService {
    @Autowired
    private SftcmMapper sftcmMapper;
    @Autowired
    private DefaultProductService defaultProductService;
    @Autowired
    private DefaultAlarmService defaultAlarmService;
    @Autowired
    private DefaultDeviceService defaultDeviceService;

    public AlarmOverviewVO getAlarmOverview(AlarmQuery query) {
        AlarmOverviewVO alarmOverviewVO = new AlarmOverviewVO();
        List<ProductAlarmNumVO> alarmList = sftcmMapper.listProductAlarmNum(query);
        if (!ObjectUtils.isEmpty(alarmList)){
            alarmOverviewVO.setAlarmList(alarmList);
            int total = alarmList.stream().mapToInt(ProductAlarmNumVO::getNum).sum();
            alarmOverviewVO.setTotal(total);
        }else{
            alarmOverviewVO.setAlarmList(new ArrayList<>());
        }
        return alarmOverviewVO;
    }

    public List<SftcmProductAlarmVO> listAlarmChartData(SftcmDailyAlarmQuery query) {
        if (query.getDayNum() <= 0 ){
            throw new ApplicationException("传入的查询天数不正确");
        }
        if (ObjectUtils.isEmpty(query.getSpecialityCode())){
            query.setSpecialityCode(SpecialityModelCodeEnum.special_facility_temperature_control_management.getCode());
        }
        Date now = new Date();
        DateTime start = DateUtil.beginOfDay(DateUtil.offsetDay(now, 1 - query.getDayNum()));
        String startTimeStr = DateUtil.formatDateTime(start);
        query.setStartTime(startTimeStr);
        query.setEndTime(DateUtil.formatDateTime(now));
        List<DayProductAlarmNumVO> dayProductAlarmNumList = sftcmMapper.listAlarmChartData(query);

        Map<String, Map<String, DayProductAlarmNumVO>> dailyAlarmNumMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(dayProductAlarmNumList)){
             dailyAlarmNumMap = dayProductAlarmNumList.stream().collect(Collectors.groupingBy(DayProductAlarmNumVO::getDay, Collectors.toMap(DayProductAlarmNumVO::getProductId, Function.identity())));
        }

        List<SftcmProductAlarmVO> res = new ArrayList<>();
        List<DateTime> rangeDayList = DateUtil.rangeToList(start, now, DateField.DAY_OF_MONTH);
        List<ProductVO> productList = defaultProductService.listProduct(new ProductQuery(query.getSpecialityCode()));

        if (!ObjectUtils.isEmpty(productList)){
            for (ProductVO productVO : productList) {
                SftcmProductAlarmVO sftcmProductAlarmVO = new SftcmProductAlarmVO();
                sftcmProductAlarmVO.setProductId(productVO.getId());
                sftcmProductAlarmVO.setProductName(productVO.getName());
                List<DayProductAlarmNumVO> productAlarmNumList = new ArrayList<>();
                for (DateTime dateTime : rangeDayList) {
                    String day = DateUtil.formatDate(dateTime);
                    DayProductAlarmNumVO tProductAlarmNumVO = dailyAlarmNumMap.getOrDefault(day, new HashMap<>()).get(productVO.getId());
                    if(ObjectUtils.isEmpty(tProductAlarmNumVO)){
                        tProductAlarmNumVO = new DayProductAlarmNumVO();
                        tProductAlarmNumVO.setProductId(productVO.getId());
                        tProductAlarmNumVO.setProductName(productVO.getName());
                        tProductAlarmNumVO.setDay(day);
                    }
                    productAlarmNumList.add(tProductAlarmNumVO);
                }
                sftcmProductAlarmVO.setAlarmList(productAlarmNumList);
                res.add(sftcmProductAlarmVO);
            }
        }
        return res;
    }

    public void exportAlarm(AlarmQuery query, HttpServletResponse response) {
        query.setDisAblePage(true);
        List<AlarmRecordVO> records = defaultAlarmService.pageAlarmHistory(query).getRecords();
        List<SftcmAlarmExportVO> res = new ArrayList<>();
        if (!ObjectUtils.isEmpty(records)){
            for (int i = 0; i < records.size(); i++) {
                AlarmRecordVO alarmRecordVO = records.get(0);
                SftcmAlarmExportVO sftcmAlarmExportVO = new SftcmAlarmExportVO();
                sftcmAlarmExportVO.setSortNo(i + 1);
                sftcmAlarmExportVO.setAddr(defaultDeviceService.getAddr(alarmRecordVO));
                sftcmAlarmExportVO.setProductName(alarmRecordVO.getProductName());
                sftcmAlarmExportVO.setDeviceName(alarmRecordVO.getName());
                sftcmAlarmExportVO.setValue(alarmRecordVO.getValue());
                sftcmAlarmExportVO.setCreateTime(DateUtil.formatDateTime(alarmRecordVO.getCreateTime()));
                res.add(sftcmAlarmExportVO);
            }
        }

        String fileName = new StringBuffer()
                .append("专用设施-")
                .append("报警")
                .append(new SimpleDateFormat("_yyyyMMddHHmmss").format(new Date()))
                .toString();
        EasyExcelUtil.exportExcelData(response,fileName,res,SftcmAlarmExportVO.class);
    }
}
